package com.pensoon.websocket;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.ara.websocket.XWebSocketService;
import com.ara.websocket.listener.WebSocketResultCallback;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements WebSocketResultCallback {
    private List<String> errors = new ArrayList<>();
    TextView tvState;
    TextView tvError;
    String WEB_SOCKET_URL = "your url";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnStart).setOnClickListener(v -> startWebSocketService());

        tvState = findViewById(R.id.tvState);
        tvError = findViewById(R.id.tvError);
        findViewById(R.id.btnLog).setOnClickListener(v -> {
            errors.clear();
            tvError.setText("");
        });
    }

    /**
     * 连接WebSocket
     */
    private void startWebSocketService() {
        if (XWebSocketService.isEmpty()) {
            XWebSocketService.startWebSocketService(this, WEB_SOCKET_URL, "isAlive");
            XWebSocketService.addCallback(this);
        } else {
            if (XWebSocketService.isClose()) {
                XWebSocketService.reconnection();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startWebSocketService();
    }

    @Override
    public void onConnectSuccess() {
        runOnUiThread(() -> {
            tvState.setText("连接状态：" + (!XWebSocketService.isClose() ? "已连接" : "未连接"));
        });
    }

    @Override
    public void onWebSocketMessage(String msg) {
        runOnUiThread(() -> {
            tvState.setText("连接状态：" + (!XWebSocketService.isClose() ? "已连接" : "未连接"));
        });
    }

    @Override
    public void onWebSocketError(Exception e) {
        runOnUiThread(() -> {
            tvState.setText("连接状态：" + (!XWebSocketService.isClose() ? "已连接" : "未连接"));
            errors.add(e.getMessage());
            StringBuilder sb = new StringBuilder();
            System.out.println("Error size ======> " + errors.size());
            sb.append("Error size : ").append(errors.size());
            sb.append("\n============================================================================\n\n");
            for (String error : errors) {
                sb.append(error);
                sb.append("\n\n");
            }
            tvError.setText(sb.toString());
        });
    }
}